// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment");

cloud.init()

function isTimeRange(beginTime, endTime) {
  var strb = beginTime.split(":");
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split(":");
  if (stre.length != 2) {
    return false;
  }

  var b = new Date()
  b.setHours(new Date().getHours() + 8);
  var e = new Date();
  e.setHours(new Date().getHours() + 8)
  var n = new Date();
  n.setHours(new Date().getHours() + 8)
  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);

  if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
    return true;
  } else {
    return false;
  }
}

//是否星期天
function isSunDay() {
  var dt = new Date()
  dt.setHours(new Date().getHours() + 8);
  if (dt.getDay() == 0) {
    //0--sunday, 6--saturday
    return true;
  } else {
    return false;
  }
}

//是否是每月的最后一天的最后一小时
function isLastDayTimeRange() {
  console.log('isLastDayTimeRange()', moment().add(8, 'hours').format('lll'))
  moment.locale('zh-cn');
  let now = moment().add(8, 'hours').valueOf();
  console.log('now', now)
  let beginTime = moment().endOf('month').subtract(1, 'hours').valueOf();
  console.log('beginTime', beginTime)
  let endTime = moment().endOf('month').valueOf();
  console.log('endTime', endTime)
  if (now >= beginTime && now <= endTime) {
    return true;
  } else {
    return false;
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  if (isSunDay() && isTimeRange('23:00', '23:59')) {
    return {
      success: false,
      message: "系统维护中，星期天23.00以后不能打卡哦~",
    }
  }
  if (isLastDayTimeRange()) {
    return {
      success: false,
      message: "系统维护中，每个月的最后一天23.00以后不能打卡哦~",
    }
  }

  const wxContext = cloud.getWXContext()
  let { openid, nickName, avatarUrl,cause } = event
  const db = cloud.database()
  moment.locale('zh-cn');
  var m = moment().utcOffset(480)
  let systemTime = m.valueOf()
  let date = m.format('lll')
  await db.collection('absence-list').add({
    data: {
      _openid: openid,
      nickName: nickName,
      avatarUrl: avatarUrl,
      cause:cause,
      systemTime: systemTime,
      date: date,
      approved: false
    },
    success: function (res) {
      console.log(res)
    }, 
    fail:function(e){
      console.log(res)
    }
  })

  return {
    success: true,
    message: "申请成功",
  }
}